﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Animation;
using UserControl = System.Windows.Controls.UserControl;

namespace BeerManagementSystem
{
    /// <summary>
    /// Interaktionslogik für AssignCard.xaml
    /// </summary>
    public partial class GameCdTab : UserControl
    {
        private static GameCdTab _instance;
        private int _rndTime;
        private Storyboard _countdownStoryboard;
        private StringAnimationUsingKeyFrames _countdownAnimation;

        public static GameCdTab Instance
        {
            get {return _instance?? (_instance = new GameCdTab());}
        }

        private GameCdTab()
        {
            InitializeComponent();
            _countdownStoryboard = new Storyboard();
            _countdownStoryboard.Completed += CountdownTimer_Completed;
            _countdownAnimation = new StringAnimationUsingKeyFrames();
            this.Background = null;
        }

        

        public int SetRoundTime
        {
            get { return _rndTime; }
            set { _rndTime = value; }
        }

        public void StartGame()
        {
            StartCountdown(CountdownDisplay, _rndTime);
        }
        private void StartCountdown(FrameworkElement target, int rndTime)
        {
            for (var i = rndTime; i >= 0; i--)
            {
                var keyTime = TimeSpan.FromSeconds(rndTime - i);
                var frame = new DiscreteStringKeyFrame(i.ToString(), KeyTime.FromTimeSpan(keyTime));
                _countdownAnimation.KeyFrames.Add(frame);
                Console.WriteLine(frame.KeyTime+ " "+ frame.Value);
            }
            _countdownAnimation.KeyFrames.Add(new DiscreteStringKeyFrame(" ", KeyTime.FromTimeSpan(TimeSpan.FromSeconds(rndTime+1))));
            Storyboard.SetTargetName(_countdownAnimation, target.Name);
            Storyboard.SetTargetProperty(_countdownAnimation, new PropertyPath(TextBlock.TextProperty));
            
            _countdownStoryboard.Children.Add(_countdownAnimation);
            _countdownStoryboard.Begin(this, true);
        }

        public void StopCountdowntimer()
        {
            _countdownStoryboard.Stop(this);
            
        }

        private void CountdownTimer_Completed(object sender, EventArgs e)
        {
            StopCountdowntimer();
            GameLost(this, e);
        }

        public event EventHandler GameLost;
    }
}
